'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import AppHeader from '@/components/ui/app-header';
import Image from 'next/image';
import { useSession } from 'next-auth/react';
import { toast } from '@/components/ui/use-toast';
import {
  CheckCircleIcon,
  ClockIcon,
  ArrowPathIcon,
  ExclamationCircleIcon,
  ChevronLeftIcon,
  PencilSquareIcon,
  TrashIcon,
  ChatBubbleLeftEllipsisIcon,
  TagIcon,
  CalendarIcon,
  UserIcon,
  PaperAirplaneIcon,
} from '@heroicons/react/24/outline';

// 任务状态标签组件
const StatusBadge = ({ status }: { status: string }) => {
  switch (status.toLowerCase()) {  // 添加toLowerCase()确保大小写一致
    case 'done':
    case 'completed':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
          <CheckCircleIcon className="mr-1 h-4 w-4" />
          已完成
        </span>
      );
    case 'in_progress':
    case 'in-progress':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
          <ArrowPathIcon className="mr-1 h-4 w-4" />
          进行中
        </span>
      );
    case 'todo':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
          <ClockIcon className="mr-1 h-4 w-4" />
          待处理
        </span>
      );
    case 'review':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
          <ClockIcon className="mr-1 h-4 w-4" />
          审核中
        </span>
      );
    default:
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
          {status}
        </span>
      );
  }
};

// 优先级标签组件
const PriorityBadge = ({ priority }: { priority: string }) => {
  switch (priority.toLowerCase()) {  // 添加toLowerCase()确保大小写一致
    case 'high':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
          <ExclamationCircleIcon className="mr-1 h-4 w-4" />
          高
        </span>
      );
    case 'medium':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
          中
        </span>
      );
    case 'low':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
          低
        </span>
      );
    case 'urgent':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-600 text-white">
          <ExclamationCircleIcon className="mr-1 h-4 w-4" />
          紧急
        </span>
      );
    default:
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
          {priority}
        </span>
      );
  }
};

// 评论类型
interface Comment {
  id: string;
  content: string;
  createdAt: string;
  parentId?: string | null;
  user: {
    id: string;
    name: string;
    image?: string;
  };
  replies?: Comment[];
  parent?: {
    id: string;
    content: string;
    userId: string;
    user: {
      id: string;
      name: string;
    };
  } | null;
}

// 项目成员类型
interface ProjectMember {
  id: string;
  userId: string;
  name: string;
  image?: string;
  email?: string;
  role: string;
}

// 任务类型定义
interface Task {
  id: string;
  title: string;
  description: string | null;
  status: string;
  priority: string;
  assignee: {
    id: string;
    name: string;
    image?: string;  // 与API返回匹配，使用image而不是avatar
    email?: string;
  } | null;
  dueDate: string | null;
  projectId: string;
  tags?: string[];  // 添加可选标记
  createdAt: string;
  updatedAt: string;
}

export default function TaskDetailPage() {
  const router = useRouter();
  const params = useParams();
  const taskId = params.id as string;
  const { data: session } = useSession();
  
  const [task, setTask] = useState<Task | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [deleteError, setDeleteError] = useState<string | null>(null);
  const [comments, setComments] = useState<Comment[]>([]);
  const [commentInput, setCommentInput] = useState('');
  const [sendingComment, setSendingComment] = useState(false);
  const [projectMembers, setProjectMembers] = useState<ProjectMember[]>([]);
  const [loadingMembers, setLoadingMembers] = useState(false);
  const [assigningUser, setAssigningUser] = useState(false);
  
  // 选择用户模态框状态
  const [showUserSelector, setShowUserSelector] = useState(false);

  // 获取任务数据
  useEffect(() => {
    const fetchTask = async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await fetch(`/api/task?id=${taskId}`);
        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`);
        }
        
        const data = await response.json();
        if (data.success) {
          setTask(data.data);
          // 获取项目成员
          fetchProjectMembers(data.data.projectId);
          // 获取任务评论
          fetchComments();
        } else {
          throw new Error(data.message || '获取任务失败');
        }
      } catch (err: any) {
        console.error('获取任务详情失败:', err);
        setError(err.message || '获取任务详情失败');
      } finally {
        setLoading(false);
      }
    };
    
    if (taskId) {
      fetchTask();
    }
  }, [taskId]);

  // 获取项目成员
  const fetchProjectMembers = async (projectId: string) => {
    setLoadingMembers(true);
    try {
      const response = await fetch(`/api/projects/${projectId}/members`);
      if (!response.ok) {
        throw new Error(`获取项目成员失败: ${response.status}`);
      }
      
      const data = await response.json();
      if (data.success) {
        setProjectMembers(data.data || []);
      } else {
        console.error('获取项目成员失败:', data.message);
      }
    } catch (err) {
      console.error('获取项目成员错误:', err);
    } finally {
      setLoadingMembers(false);
    }
  };

  // 获取任务评论
  const fetchComments = async () => {
    try {
      const response = await fetch(`/api/task/${taskId}/comments`);
      if (!response.ok) {
        // 如果API未实现，使用空数组而不是报错
        setComments([]);
        return;
      }
      
      const data = await response.json();
      if (data.success) {
        setComments(data.data || []);
      } else {
        setComments([]);
      }
    } catch (err) {
      console.error('获取评论失败:', err);
      setComments([]);
    }
  };

  // 发送评论
  const submitComment = async () => {
    if (!commentInput.trim() || !session?.user?.id) return;
    
    setSendingComment(true);
    try {
      // 创建临时评论 (用于UI显示)
      const tempComment = {
        id: `temp-${Date.now()}`,
        content: commentInput,
        createdAt: new Date().toISOString(),
        user: {
          id: session.user.id as string,
          name: session.user.name || '当前用户',
          image: session.user.image
        }
      };
      
      // 添加到界面上
      setComments(prev => [...prev, tempComment]);
      
      // 清空输入框
      setCommentInput('');
      
      // 发送评论请求
      const response = await fetch(`/api/comments`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          content: commentInput,
          taskId: taskId,
          projectId: task?.projectId
        })
      });
      
      // 如果API未实现，仍然保留临时评论
      if (!response.ok) {
        toast({
          title: "评论功能即将上线",
          description: "评论功能正在开发中，敬请期待！",
          variant: "default"
        });
        return;
      }
      
      // 如果API实现了，重新获取评论列表
      const data = await response.json();
      if (data.success) {
        fetchComments();
      } else {
        throw new Error(data.message || '发送评论失败');
      }
    } catch (err) {
      console.error('评论发送失败:', err);
      toast({
        title: "评论发送失败",
        description: "请稍后再试",
        variant: "destructive"
      });
    } finally {
      setSendingComment(false);
    }
  };

  // 分配负责人
  const assignUser = async (userId: string) => {
    if (!task) return;
    
    setAssigningUser(true);
    try {
      const response = await fetch(`/api/task?id=${taskId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          assigneeId: userId
        })
      });
      
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`);
      }
      
      const data = await response.json();
      if (data.success) {
        // 更新任务数据
        setTask(data.data);
        toast({
          title: "已分配负责人",
          description: "任务负责人已更新",
          variant: "default"
        });
      } else {
        throw new Error(data.message || '分配负责人失败');
      }
    } catch (err: any) {
      console.error('分配负责人失败:', err);
      toast({
        title: "分配失败",
        description: err.message || '分配负责人失败',
        variant: "destructive"
      });
    } finally {
      setAssigningUser(false);
      setShowUserSelector(false);
    }
  };

  // 处理任务删除
  const handleDeleteTask = async () => {
    if (!confirm('确定要删除此任务吗？此操作无法撤销。')) {
      return;
    }
    
    setIsDeleting(true);
    setDeleteError(null);
    
    try {
      const response = await fetch(`/api/task?id=${taskId}`, {
        method: 'DELETE',
      });
      
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`);
      }
      
      const data = await response.json();
      if (data.success) {
        // 删除成功，返回任务列表页面
        router.push('/task');
      } else {
        throw new Error(data.message || '删除任务失败');
      }
    } catch (err: any) {
      console.error('删除任务失败:', err);
      setDeleteError(err.message || '删除任务失败');
    } finally {
      setIsDeleting(false);
    }
  };

  // 处理状态更新
  const handleStatusChange = async (newStatus: string) => {
    if (!task) return;
    
    // 转换状态为大写格式，与API一致
    let apiStatus: string;
    switch(newStatus.toLowerCase()) {
      case 'todo':
        apiStatus = 'TODO';
        break;
      case 'in-progress':
        apiStatus = 'IN_PROGRESS';
        break;
      case 'completed':
        apiStatus = 'DONE';
        break;
      default:
        apiStatus = newStatus.toUpperCase();
    }
    
    try {
      const response = await fetch(`/api/task?id=${taskId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...task,
          status: apiStatus,
        }),
      });
      
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`);
      }
      
      const data = await response.json();
      if (data.success) {
        setTask(data.data);
      } else {
        throw new Error(data.message || '更新任务状态失败');
      }
    } catch (err: any) {
      console.error('更新任务状态失败:', err);
      alert(`更新任务状态失败: ${err.message}`);
    }
  };

  return (
    <div className="min-h-screen">
      <main className="py-6 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
        <div className="mb-6">
          <button
            type="button"
            onClick={() => router.back()}
            className="inline-flex items-center px-3 py-1 border border-transparent text-sm font-medium rounded-md text-gray-700 hover:bg-gray-100 focus:outline-none"
          >
            <ChevronLeftIcon className="h-5 w-5 mr-1" />
            返回
          </button>
        </div>
        
        {loading ? (
          <div className="flex justify-center py-12">
            <div className="animate-pulse text-gray-500">加载任务中...</div>
          </div>
        ) : error ? (
          <div className="bg-red-50 p-4 rounded-md">
            <div className="flex">
              <div className="flex-shrink-0">
                <ExclamationCircleIcon className="h-5 w-5 text-red-400" aria-hidden="true" />
              </div>
              <div className="ml-3">
                <h3 className="text-sm font-medium text-red-800">加载任务时出错</h3>
                <div className="mt-2 text-sm text-red-700">
                  <p>{error}</p>
                </div>
              </div>
            </div>
          </div>
        ) : task ? (
          <>
            <div className="flex flex-col md:flex-row md:items-center md:justify-between">
              <div>
                <h1 className="text-2xl font-bold text-gray-900">{task.title}</h1>
                <div className="mt-2 flex items-center space-x-2">
                  <StatusBadge status={task.status} />
                  <PriorityBadge priority={task.priority} />
                </div>
              </div>
              <div className="mt-4 md:mt-0 flex space-x-3">
                <button
                  type="button"
                  onClick={() => router.push(`/task/edit/${taskId}`)}
                  className="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
                >
                  <PencilSquareIcon className="h-5 w-5 mr-2 text-gray-500" />
                  编辑任务
                </button>
                <button
                  type="button"
                  onClick={handleDeleteTask}
                  disabled={isDeleting}
                  className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700 focus:outline-none disabled:opacity-50"
                >
                  <TrashIcon className="h-5 w-5 mr-2" />
                  {isDeleting ? '删除中...' : '删除任务'}
                </button>
              </div>
            </div>
            
            {deleteError && (
              <div className="mt-4 bg-red-50 p-4 rounded-md">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <ExclamationCircleIcon className="h-5 w-5 text-red-400" aria-hidden="true" />
                  </div>
                  <div className="ml-3">
                    <h3 className="text-sm font-medium text-red-800">删除任务时出错</h3>
                    <div className="mt-2 text-sm text-red-700">
                      <p>{deleteError}</p>
                    </div>
                  </div>
                </div>
              </div>
            )}
            
            <div className="mt-6 bg-white shadow rounded-lg overflow-hidden">
              {/* 任务状态切换 */}
              <div className="px-4 py-5 sm:px-6 border-b border-gray-200">
                <h3 className="text-lg font-medium text-gray-900">任务状态</h3>
                <div className="mt-3 flex space-x-3">
                  <button
                    type="button"
                    onClick={() => handleStatusChange('todo')}
                    className={`px-4 py-2 text-sm font-medium rounded-md ${
                      task.status.toUpperCase() === 'TODO'
                        ? 'bg-gray-100 text-gray-900 border-2 border-gray-300'
                        : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50 border border-gray-300'
                    }`}
                  >
                    <ClockIcon className="inline-block h-4 w-4 mr-1" />
                    待处理
                  </button>
                  <button
                    type="button"
                    onClick={() => handleStatusChange('in-progress')}
                    className={`px-4 py-2 text-sm font-medium rounded-md ${
                      task.status.toUpperCase() === 'IN_PROGRESS'
                        ? 'bg-blue-100 text-blue-800 border-2 border-blue-300'
                        : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50 border border-gray-300'
                    }`}
                  >
                    <ArrowPathIcon className="inline-block h-4 w-4 mr-1" />
                    进行中
                  </button>
                  <button
                    type="button"
                    onClick={() => handleStatusChange('review')}
                    className={`px-4 py-2 text-sm font-medium rounded-md ${
                      task.status.toUpperCase() === 'REVIEW'
                        ? 'bg-purple-100 text-purple-800 border-2 border-purple-300'
                        : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50 border border-gray-300'
                    }`}
                  >
                    <ArrowPathIcon className="inline-block h-4 w-4 mr-1" />
                    审核中
                  </button>
                  <button
                    type="button"
                    onClick={() => handleStatusChange('completed')}
                    className={`px-4 py-2 text-sm font-medium rounded-md ${
                      task.status.toUpperCase() === 'DONE'
                        ? 'bg-green-100 text-green-800 border-2 border-green-300'
                        : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50 border border-gray-300'
                    }`}
                  >
                    <CheckCircleIcon className="inline-block h-4 w-4 mr-1" />
                    已完成
                  </button>
                </div>
              </div>
              
              {/* 任务详情 */}
              <div className="px-4 py-5 sm:px-6">
                <dl className="grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2">
                  <div className="sm:col-span-2">
                    <dt className="text-sm font-medium text-gray-500">描述</dt>
                    <dd className="mt-1 text-sm text-gray-900 whitespace-pre-wrap">
                      {task.description || '无描述'}
                    </dd>
                  </div>
                  
                  <div>
                    <dt className="text-sm font-medium text-gray-500 flex items-center">
                      <UserIcon className="h-4 w-4 mr-1" />
                      负责人
                    </dt>
                    <dd className="mt-1 text-sm text-gray-900">
                      {task.assignee ? (
                        <div className="flex items-center">
                          <div className="h-8 w-8 rounded-full overflow-hidden bg-gray-100">
                            {task.assignee.image ? (
                              <Image
                                src={task.assignee.image}
                                alt={task.assignee.name}
                                width={32}
                                height={32}
                                className="h-full w-full object-cover"
                              />
                            ) : (
                              <div className="h-full w-full flex items-center justify-center">
                                <UserIcon className="h-4 w-4 text-gray-400" />
                              </div>
                            )}
                          </div>
                          <span className="ml-2">{task.assignee.name}</span>
                        </div>
                      ) : (
                        <button
                          className="text-blue-500 hover:underline flex items-center"
                          onClick={() => setShowUserSelector(true)}
                          disabled={assigningUser}
                        >
                          {assigningUser ? '分配中...' : '分配负责人'}
                        </button>
                      )}
                    </dd>
                    
                    {task.assignee && (
                      <button
                        className="mt-2 text-xs text-blue-500 hover:underline"
                        onClick={() => setShowUserSelector(true)}
                        disabled={assigningUser}
                      >
                        {assigningUser ? '更改中...' : '更改负责人'}
                      </button>
                    )}
                  </div>
                  
                  <div>
                    <dt className="text-sm font-medium text-gray-500 flex items-center">
                      <CalendarIcon className="h-4 w-4 mr-1" />
                      截止日期
                    </dt>
                    <dd className="mt-1 text-sm text-gray-900">
                      {task.dueDate ? new Date(task.dueDate).toLocaleDateString('zh-CN') : '无截止日期'}
                    </dd>
                  </div>
                  
                  <div>
                    <dt className="text-sm font-medium text-gray-500 flex items-center">
                      <TagIcon className="h-4 w-4 mr-1" />
                      标签
                    </dt>
                    <dd className="mt-1 text-sm text-gray-900">
                      {task.tags && task.tags.length > 0 ? (
                        <div className="flex flex-wrap gap-1">
                          {task.tags.map((tag) => (
                            <span
                              key={tag}
                              className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800"
                            >
                              {tag}
                            </span>
                          ))}
                        </div>
                      ) : (
                        '无标签'
                      )}
                    </dd>
                  </div>
                  
                  <div>
                    <dt className="text-sm font-medium text-gray-500">创建时间</dt>
                    <dd className="mt-1 text-sm text-gray-900">
                      {new Date(task.createdAt).toLocaleString('zh-CN')}
                    </dd>
                  </div>
                  
                  <div>
                    <dt className="text-sm font-medium text-gray-500">最后更新</dt>
                    <dd className="mt-1 text-sm text-gray-900">
                      {new Date(task.updatedAt).toLocaleString('zh-CN')}
                    </dd>
                  </div>
                </dl>
              </div>
              
              {/* 评论区 */}
              <div className="px-4 py-5 sm:px-6 border-t border-gray-200">
                <h3 className="text-lg font-medium text-gray-900 flex items-center">
                  <ChatBubbleLeftEllipsisIcon className="h-5 w-5 mr-2" />
                  评论
                </h3>
                
                {/* 评论列表 */}
                <div className="mt-4 space-y-6">
                  {comments.map((comment) => (
                    <div key={comment.id} className="space-y-4">
                      <div className="flex space-x-3">
                        <div className="flex-shrink-0">
                          <div className="h-10 w-10 rounded-full overflow-hidden bg-gray-100">
                            {comment.user.image ? (
                              <Image
                                src={comment.user.image}
                                alt={comment.user.name}
                                width={40}
                                height={40}
                                className="h-full w-full object-cover"
                              />
                            ) : (
                              <div className="h-full w-full flex items-center justify-center">
                                <UserIcon className="h-5 w-5 text-gray-400" />
                              </div>
                            )}
                          </div>
                        </div>
                        <div className="flex-grow">
                          <div className="flex items-center justify-between">
                            <div>
                              <span className="font-medium text-gray-900">{comment.user.name}</span>
                              <span className="ml-2 text-xs text-gray-500">
                                {new Date(comment.createdAt).toLocaleString('zh-CN')}
                              </span>
                            </div>
                            <button
                              className="text-xs text-blue-500 hover:text-blue-700"
                              onClick={() => {
                                // 添加新的输入字段
                                const replyTextArea = document.getElementById(`reply-${comment.id}`);
                                if (replyTextArea) {
                                  replyTextArea.classList.toggle('hidden');
                                  replyTextArea.querySelector('textarea')?.focus();
                                }
                              }}
                            >
                              回复
                            </button>
                          </div>
                          <div className="mt-1 text-sm text-gray-700">
                            {comment.content}
                          </div>
                          
                          {/* 回复输入框 */}
                          <div id={`reply-${comment.id}`} className="mt-2 hidden">
                            <div className="flex">
                              <div className="flex-grow relative border border-gray-300 rounded-md">
                                <textarea
                                  className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                                  rows={2}
                                  placeholder={`回复 ${comment.user.name}...`}
                                  id={`reply-text-${comment.id}`}
                                />
                                <div className="mt-1 flex justify-end">
                                  <button
                                    type="button"
                                    className="px-3 py-1 text-xs text-white bg-blue-500 rounded-md hover:bg-blue-600"
                                    onClick={async () => {
                                      const textarea = document.getElementById(`reply-text-${comment.id}`) as HTMLTextAreaElement;
                                      if (textarea && textarea.value.trim()) {
                                        try {
                                          const response = await fetch('/api/comments', {
                                            method: 'POST',
                                            headers: { 'Content-Type': 'application/json' },
                                            body: JSON.stringify({
                                              content: textarea.value.trim(),
                                              parentId: comment.id,
                                              taskId: taskId,
                                              projectId: task?.projectId
                                            }),
                                          });
                                          
                                          if (response.ok) {
                                            const result = await response.json();
                                            // 显示成功消息
                                            toast({
                                              title: "评论成功",
                                              description: "您的回复已添加",
                                              variant: "default"
                                            });
                                            
                                            // 清空输入框并隐藏
                                            textarea.value = '';
                                            document.getElementById(`reply-${comment.id}`)?.classList.add('hidden');
                                            
                                            // 重新加载评论
                                            fetchComments();
                                          }
                                        } catch (error) {
                                          console.error('回复评论失败:', error);
                                        }
                                      }
                                    }}
                                  >
                                    发送回复
                                  </button>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      {/* 回复列表 */}
                      {comment.replies && comment.replies.length > 0 && (
                        <div className="pl-12 space-y-3">
                          {comment.replies.map((reply) => (
                            <div key={reply.id} className="flex space-x-3 bg-gray-50 p-3 rounded-md">
                              <div className="flex-shrink-0">
                                <div className="h-8 w-8 rounded-full overflow-hidden bg-gray-100">
                                  {reply.user.image ? (
                                    <Image
                                      src={reply.user.image}
                                      alt={reply.user.name}
                                      width={32}
                                      height={32}
                                      className="h-full w-full object-cover"
                                    />
                                  ) : (
                                    <div className="h-full w-full flex items-center justify-center">
                                      <UserIcon className="h-4 w-4 text-gray-400" />
                                    </div>
                                  )}
                                </div>
                              </div>
                              <div className="flex-grow">
                                <div className="flex items-center">
                                  <span className="font-medium text-gray-900">{reply.user.name}</span>
                                  <span className="ml-2 text-xs text-gray-500">
                                    {new Date(reply.createdAt).toLocaleString('zh-CN')}
                                  </span>
                                </div>
                                <div className="mt-1 text-sm text-gray-700">
                                  {reply.content}
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  ))}
                  
                  {comments.length === 0 && (
                    <div className="text-center py-6 text-gray-500">
                      还没有评论，添加第一条评论吧！
                    </div>
                  )}
                </div>
                
                {/* 添加评论 */}
                {session?.user && (
                  <div className="mt-6 flex">
                    <div className="flex-shrink-0 mr-3">
                      <div className="h-10 w-10 rounded-full overflow-hidden bg-gray-100">
                        {session.user.image ? (
                          <Image
                            src={session.user.image}
                            alt={session.user.name || '用户头像'}
                            width={40}
                            height={40}
                            className="h-full w-full object-cover"
                          />
                        ) : (
                          <div className="h-full w-full flex items-center justify-center">
                            <UserIcon className="h-5 w-5 text-gray-400" />
                          </div>
                        )}
                      </div>
                    </div>
                    <div className="flex-grow relative">
                      <textarea
                        className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                        rows={3}
                        placeholder="添加评论..."
                        value={commentInput}
                        onChange={(e) => setCommentInput(e.target.value)}
                      />
                      <button
                        type="button"
                        className="mt-2 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none disabled:opacity-50"
                        onClick={async () => {
                          await submitComment();
                          toast({
                            title: "评论成功",
                            description: "您的评论已添加",
                            variant: "default"
                          });
                        }}
                        disabled={sendingComment || !commentInput.trim()}
                      >
                        <PaperAirplaneIcon className="h-4 w-4 mr-2" />
                        {sendingComment ? '发送中...' : '发送评论'}
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </div>
            
            {/* 成员选择模态框 */}
            {showUserSelector && (
              <div className="fixed inset-0 z-10 overflow-y-auto">
                <div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                  {/* 背景遮罩 */}
                  <div 
                    className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
                    onClick={() => setShowUserSelector(false)}
                  ></div>
                  
                  {/* 模态框居中技巧 */}
                  <span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
                  
                  {/* 模态框内容 */}
                  <div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                    <div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                      <div className="sm:flex sm:items-start">
                        <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
                          <h3 className="text-lg leading-6 font-medium text-gray-900">
                            选择负责人
                          </h3>
                          <div className="mt-4">
                            {loadingMembers ? (
                              <div className="text-center py-4">加载成员中...</div>
                            ) : projectMembers.length > 0 ? (
                              <div className="max-h-60 overflow-y-auto">
                                <ul className="divide-y divide-gray-200">
                                  {projectMembers.map((member) => (
                                    <li 
                                      key={member.userId} 
                                      className="py-3 px-2 hover:bg-gray-50 flex items-center cursor-pointer"
                                      onClick={() => assignUser(member.userId)}
                                    >
                                      <div className="h-10 w-10 rounded-full overflow-hidden bg-gray-100 mr-3">
                                        {member.image ? (
                                          <Image
                                            src={member.image}
                                            alt={member.name}
                                            width={40}
                                            height={40}
                                            className="h-full w-full object-cover"
                                          />
                                        ) : (
                                          <div className="h-full w-full flex items-center justify-center">
                                            <UserIcon className="h-5 w-5 text-gray-400" />
                                          </div>
                                        )}
                                      </div>
                                      <div>
                                        <p className="font-medium text-gray-900">{member.name}</p>
                                        <p className="text-xs text-gray-500">{member.role}</p>
                                      </div>
                                    </li>
                                  ))}
                                </ul>
                              </div>
                            ) : (
                              <div className="text-center py-4 text-gray-500">
                                未找到项目成员
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                    <div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                      <button 
                        type="button"
                        onClick={() => setShowUserSelector(false)}
                        className="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
                      >
                        取消
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </>
        ) : null}
      </main>
    </div>
  );
} 